iT邦幫忙

2025 iThome 鐵人賽

DAY 19
0
自我挑戰組

Leetcode 小白練功坊系列 第 19

[DAY19] 495. Teemo Attacking

  • 分享至 

  • xImage
  •  

題目連結(https://leetcode.com/problems/teemo-attacking/description/)

Our hero Teemo is attacking an enemy Ashe with poison attacks! When Teemo attacks Ashe, Ashe gets poisoned for a exactly duration seconds. More formally, an attack at second t will mean Ashe is poisoned during the inclusive time interval [t, t + duration - 1]. If Teemo attacks again before the poison effect ends, the timer for it is reset, and the poison effect will end duration seconds after the new attack.

You are given a non-decreasing integer array timeSeries, where timeSeries[i] denotes that Teemo attacks Ashe at second timeSeries[i], and an integer duration.

Return the total number of seconds that Ashe is poisoned.

每日一題是water bottle2 改挑一題 easy 分享

1. Repeat(題目重複確認)

  • 輸入: non-decreasing integer array timeSeries, 整數 duration
  • 輸出: 總中毒時長
  • 前提:
    • 1 <= timeSeries.length <= 104
    • 0 <= timeSeries[i], duration <= 107
    • timeSeries is sorted in non-decreasing order.

2. Examples(舉例確認理解)

Input: timeSeries = [1,4], duration = 2
Output: 4
Explanation: Teemo's attacks on Ashe go as follows:
- At second 1, Teemo attacks, and Ashe is poisoned for seconds 1 and 2.
- At second 4, Teemo attacks, and Ashe is poisoned for seconds 4 and 5.
Ashe is poisoned for seconds 1, 2, 4, and 5, which is 4 seconds in total.

時間軸: 0 1 2 3 4 5 6
攻擊: ↓ ↓
中毒: [--] [--]
結果: 1,2,4,5 = 4秒


3. Approach(解題思路)

**方法 :**迭代模擬法 (Iterative Simulation)

  • 遍歷攻擊序列:對每次攻擊(除最後一次)檢查與下次攻擊的時間間隔
  • 計算實際中毒時間
    • 如果間隔 ≥ duration:貢獻完整 duration
    • 如果間隔 < duration:只貢獻間隔時間(因為被下次攻擊重置)
  • 處理最後一次攻擊:中毒完整 duration
  • 時間複雜度:O(n)
  • 空間複雜度:O(1)

4. Code(C++)

class Solution {
public:
    int findPoisonedDuration(vector<int>& timeSeries, int duration) {
				int result = 0;
        int gap = 0;
        for(int i = 0; i < timeSeries.size()-1; i++){
            gap = timeSeries[i+1] - timeSeries[i];
				    result += min(duration, gap);
				}
        result += duration; //LAST ATTACK
				return result;
    }
};

5. Test 範例

timeSeries = [1, 2, 3, 4, 5]
duration = 5
result = sol.findPoisonedDuration(timeSeries, duration)
print(f"Example: {result}")

# Expected: 9

print(f"說明: 連續攻擊不斷重置,最後一次攻擊完整5秒")
print(f"實際: 1+1+1+1+5 = 9秒\n")


6. 相關題目與延伸概念

7. 補充:語法&注意事項

用 min(duration, gap) 控制,不用再額外寫判斷式就能處理兩種情況

 for(int i = 0; i < timeSeries.size()-1; i++){
            gap = timeSeries[i+1] - timeSeries[i];
				    result += min(duration, gap);
				}

ps. 部分內容經 AI 協助整理


上一篇
[DAY18] 1518. Water Bottles
下一篇
[DAY20] 383. Ransom Note
系列文
Leetcode 小白練功坊22
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言